import { isLocalDev } from '@umijs/utils';
import fs from 'fs';
import path from 'path';
import { IApi, IUIModule } from '../../types';
// @ts-ignore
import sirv from '../../../compiled/sirv';

const ENTRY_PATH = '/__umi_ui/entry';

export default (api: IApi) => {
  api.describe({
    enableBy() {
      return api.name === 'dev' && api.userConfig.ui;
    },
    config: {
      schema({ zod }) {
        return zod.object({});
      },
    },
  });

  const uiDir = path.dirname(require.resolve('@umijs/ui/package.json'));

  api.onCheck(() => {
    if (!fs.existsSync(path.join(uiDir, 'dist'))) {
      if (isLocalDev()) {
        throw new Error(
          `@umijs/ui not built, please run 'pnpm ui:build' first.`,
        );
      } else {
        throw new Error(`@umijs/ui not found, please fill an issue on github.`);
      }
    }
  });

  api.onBeforeMiddleware(({ app }) => {
    app.use(
      ENTRY_PATH,
      sirv(path.join(uiDir, 'dist'), {
        etag: true,
        dev: true,
        single: true,
      }),
    );
  });

  api.addHTMLStyles(() => {
    return [
      `
#umi-ui-container.umi-ui-container-show {
  display: block;
}
#umi-ui-container {
  position: fixed;
  bottom: 10px;
  left: calc(10vw + 10px);
  height: calc(75vh - 20px);
  width: calc(80vw - 20px);
  display: none;
  border-radius: .5rem;
  z-index: 2147483646;
}
#umi-ui-toggle-btn {
  width: 40px;
  height: 40px;
  position: fixed;
  left: 50%;
  bottom: -20px;
  transform: translateX(-50%);
  cursor: pointer;
  display: flex;
  background-size: 100% 100%;
  background-image: url('');
  transition: bottom 0.1s linear;
  z-index: 2147483647;
}
#umi-ui-toggle-btn:hover {
  bottom: 0px;
}
#umi-ui-iframe {
  width: 100%;
  height: 100%;
  outline: none;
  border: 1px solid rgba(125,125,125,0.2);
  border-radius: 0.5rem;
}
      `,
    ];
  });

  api.modifyAppData(async (memo) => {
    const uiModules: IUIModule =
      (await api.applyPlugins({
        key: 'addUIModules',
        initialValue: [],
      })) ?? [];
    memo.ui = {
      modules: uiModules,
    };
    return memo;
  });

  api.onGenerateFiles(({ isFirstTime }) => {
    if (!isFirstTime) return;
    api.writeTmpFile({
      path: 'core/ui.ts',
      noPluginDir: true,
      content: `
// button and iframe
const container = document.createElement('div')
container.id = 'umi-ui-container';
const iframe = document.createElement('iframe');
iframe.id = 'umi-ui-iframe';
iframe.src = '${process.env.DEBUG_UMI_UI_PATH || ENTRY_PATH}';
const uiBtn = document.createElement('div');
uiBtn.id = 'umi-ui-toggle-btn';
container.appendChild(iframe);
document.body.appendChild(uiBtn);
document.body.appendChild(container);
uiBtn.addEventListener('click', () => {
  container.classList.toggle('umi-ui-container-show');
});
      `,
    });
  });
  api.addEntryImports(() => {
    return [{ source: '@@/core/ui' }];
  });
};
